package org.meb.spdwldr;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.jsoup.Jsoup;
import org.meb.spdwldr.parser.EventSourceParser;
import org.meb.spdwldr.parser.EventSourceParserChain;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/task")
public class TaskController {

	private static final List<String> sources;
	private static final EventSourceParser parser = new EventSourceParserChain();

	static {
		sources = new ArrayList<String>();
		sources.add("http://www.sportowefakty.pl/live/zuzel");
		// sources.add("http://www.sportowefakty.pl/live/zuzel/enea-ekstraliga");
		// sources.add("http://www.sportowefakty.pl/live/zuzel/elite-league");
	}

	@RequestMapping("/scan")
	public String scanSources() throws IOException {
		EventSourceDao dao = new EventSourceDao();
		for (String source : sources) {
			System.out.println("[ " + source + " ]");
			String content = Jsoup.connect(source).execute().body();
			List<EventSource> eventSources = parser.parse(content);
			for (EventSource eventSource : eventSources) {
				EventSource persistent = dao.find(eventSource.getEventUri());
				Date operDate = DateUtils.truncate(new Date(), Calendar.SECOND);
				if (persistent == null) {
					eventSource.setInsertDate(operDate);
					eventSource.setUpdateDate(operDate);
					dao.persist(eventSource);
				} else {
					boolean merge = false;
					if (eventSource.getEventDate() != null) {
						persistent.setEventDate(eventSource.getEventDate());
						persistent.setUpdateDate(operDate);
						merge = true;
					}
					if (eventSource.getEventGroup() != null && persistent.getEventGroup() == null) {
						persistent.setEventGroup(eventSource.getEventGroup());
						persistent.setUpdateDate(operDate);
						merge = true;
					}
					if (merge) {
						persistent.setUpdateDate(operDate);
						dao.merge(persistent);
					}
				}
			}
		}
		return "redirect:/event/list";
	}

	@RequestMapping("/corr")
	public String correctSources() {
		List<EventSource> eventSources = new EventSourceDao().find(new EventSourceQuery());
		for (EventSource eventSource : eventSources) {
			Date date = eventSource.getEventDate();
			Date operDate = DateUtils.truncate(new Date(), Calendar.SECOND);
			if (date != null) {
				eventSource.setEventDate(DateUtils.truncate(date, Calendar.DAY_OF_MONTH));
				if (eventSource.getEventTime() == null) {
					eventSource.setEventTime(date);
				}
				eventSource.setUpdateDate(operDate);
				new EventSourceDao().merge(eventSource);
			}
		}
		return "redirect:/event/list";
	}
}
